package com.tcoiss.datafactory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tcoiss.common.core.domain.R;
import com.tcoiss.common.core.enums.ErroEnums;
import com.tcoiss.common.core.exception.CustomException;
import com.tcoiss.common.component.api.RemoteApiService;
import com.tcoiss.common.component.api.model.ApiParam;
import com.tcoiss.common.component.api.model.K3Result;
import com.tcoiss.datafactory.domain.BusTable;
import com.tcoiss.datafactory.domain.OaK3Mapping;
import com.tcoiss.datafactory.mapper.OaK3MappingMapper;
import com.tcoiss.datafactory.service.IBusTableService;
import com.tcoiss.datafactory.service.IOaK3MappingService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * OA同步星空映射Service业务层处理
 *
 * @author zw
 * @date 2021-05-23
 */
@Service
public class OaK3MappingServiceImpl extends ServiceImpl<OaK3MappingMapper, OaK3Mapping> implements IOaK3MappingService {

    @Autowired
    private RemoteApiService remoteApiService;

    @Autowired
    private IBusTableService iBusTableService;

    @Override
    public List<OaK3Mapping> queryList(OaK3Mapping oaK3Mapping) {
        LambdaQueryWrapper<OaK3Mapping> lqw = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(oaK3Mapping.getTableName())) {
            lqw.eq(OaK3Mapping::getTableName, oaK3Mapping.getTableName());
        }
        if (StringUtils.isNotBlank(oaK3Mapping.getOaFormName())) {
            lqw.like(OaK3Mapping::getOaFormName, oaK3Mapping.getOaFormName());
        }
        if (StringUtils.isNotBlank(oaK3Mapping.getK3FormName())) {
            lqw.like(OaK3Mapping::getK3FormName, oaK3Mapping.getK3FormName());
        }
        if (oaK3Mapping.getDataLevel() != null) {
            lqw.eq(OaK3Mapping::getDataLevel, oaK3Mapping.getDataLevel());
        } else {
            lqw.eq(OaK3Mapping::getDataLevel, 1);
        }
        return this.list(lqw);
    }

    @Override
    public boolean saveMapping(OaK3Mapping oaK3Mapping) {
        LambdaQueryWrapper<OaK3Mapping> lam = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(oaK3Mapping.getOaFormId())) {
            lam.eq(OaK3Mapping::getOaFormId, oaK3Mapping.getOaFormId());
        }
        if (this.list(lam).size() > 0) {
            throw new CustomException(ErroEnums.DATAERRO.getCode(), new String[]{oaK3Mapping.getTableName()}, ErroEnums.DATAERRO.getInfo() + "OA表单标识已存在");
        }
        return this.save(oaK3Mapping);
    }

    @Override
    public boolean syncK3BillByMapping(Map<String, Object> oaMap) {
        //获取主表集合
        Map<String, Object> mainTableMap = (HashMap) oaMap.get("main");
        //获取子表集合
        Map<String, Object> detailTableMap = (HashMap) oaMap.get("detail");
        ArrayList<HashMap> dt1List = (ArrayList<HashMap>) detailTableMap.get("dt1");
        String oaFormId = mainTableMap.get("main").toString();
        //根据oa表单ID获取映射关系
        LambdaQueryWrapper<OaK3Mapping> lqw = Wrappers.lambdaQuery();
        lqw.eq(OaK3Mapping::getOaFormId, oaFormId);
        OaK3Mapping mapping = this.getOne(lqw);
        String tableName = mapping.getTableName();
        BusTable table = iBusTableService.getBusTableByName(tableName);
        if (mapping == null) {
            throw new CustomException(ErroEnums.DATAERRO.getCode(), new Object[]{oaFormId}, ErroEnums.DATAERRO.getInfo() + "未查询到对应的映射关系");
        }
        // TODO 根据映射表获取对应的接口参数 ,通过字段关系表解析获取json数据 content
        ApiParam apiParam = new ApiParam();
        apiParam.setApiCode(table.getSyncApiCode());
        Map<String, Object> map = new HashMap<>();
        map.put("formId", mapping.getK3FormId());
        map.put("content", "");
        apiParam.setParam(map);
        R<K3Result> r = remoteApiService.executeK3Api(apiParam);
        if (r.getCode() == 200) {
            K3Result k3Result = r.getData();
            if (k3Result.getCode() == "0") {//成功
                return true;
            } else {
                throw new CustomException(ErroEnums.APIERRO.getCode(), new Object[]{oaFormId},ErroEnums.APIERRO.getInfo() + "调用星空接口异常" + k3Result.getErrorMsg());
            }
        } else {
            throw new CustomException(ErroEnums.APIERRO.getCode(), new Object[]{oaFormId},ErroEnums.APIERRO.getInfo() + "调用接口服务异常" + r.getMsg());
        }
    }


    @Override
    public boolean updateMappingById(OaK3Mapping oaK3Mapping) {
        LambdaQueryWrapper<OaK3Mapping> lam = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(oaK3Mapping.getOaFormId())) {
            lam.eq(OaK3Mapping::getOaFormId, oaK3Mapping.getOaFormId());
        }
        lam.ne(OaK3Mapping::getId, oaK3Mapping.getId());
        if (this.list(lam).size() > 0) {
            throw new CustomException(ErroEnums.DATAERRO.getCode(), new String[]{oaK3Mapping.getTableName()},ErroEnums.DATAERRO.getInfo() + "OA表单标识已存在");
        }
        return this.updateById(oaK3Mapping);
    }

    @Override
    public boolean updateUseStatus(List<Long> asList, Integer status) {
        if (asList != null & status != null) {
            for (Long id : asList) {
                OaK3Mapping ew = getById(id);
                if (ew.getDataLevel() != status) {
                    ew.setDataLevel(status);
                    this.updateById(ew);
                }
            }
            return true;
        }
        return false;
    }
}
